package com.qf.CompletableFuture;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;

public class Demo05 {

    public static void main(String[] args) throws InterruptedException {

//        CountDownLatch countDownLatch = new CountDownLatch(5);
//
//        for (int i = 0; i < 5; i++) {
//            new Thread(() -> {
//                try {
//                    Thread.sleep(1000* new Random().nextInt(5));
//                System.out.println("同学:" + Thread.currentThread().getName() + "离开教室");
//                    countDownLatch.countDown();
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }, i + "").start();
//        }
//
//        System.out.println("阿姨等待学员全部离开中。。。");
//        countDownLatch.await();
//        System.out.println("阿姨关门，下班。。");


        CyclicBarrier cyclicBarrier = new CyclicBarrier(5, () -> {
            System.out.println("5个运动员全部准备好了。。。，裁判发抢");
        });

        for (int i = 0; i < 5; i++) {
            int time = i;
            new Thread(() -> {
                String name = Thread.currentThread().getName();
                System.out.println("运动员" + name + "开始准备");
                try {
                    Thread.sleep(1000 * time);
                    System.out.println("运动员" + name + "准备完成");

                    cyclicBarrier.await(); // 等待其他运动员准备
                    System.out.println("运动员" + name + "开始跑。。。");

                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }

            }, i + "").start();
        }

//        final CyclicBarrier cyclicBarrier = new CyclicBarrier(10,()->{
//            System.out.println("所有人都准备好了裁判开始了");
//        });
//        for (int i = 0; i < 10; i++) {
//            //lambda中只能只用final的变量
//            final int times = i;
//            new Thread(() -> {
//                try {
//                    System.out.println("子线程" + Thread.currentThread().getName() + "正在准备");
//                    Thread.sleep(1000 * times);
//                    System.out.println("子线程" + Thread.currentThread().getName() + "准备好了");
//                    cyclicBarrier.await();
//                    System.out.println("子线程" + Thread.currentThread().getName() + "开始跑了");
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                } catch (BrokenBarrierException e) {
//                    e.printStackTrace();
//                }
//            }).start();
//        }

    }
}
